/**
 * 警察
 */
var app = angular.module('app.controllers-police', []);

app.controller('PoliceGroupCtrl', ['$scope', 'GroupService', '$cordovaToast', '$ionicModal', 'GroupService', '$timeout',
  'AppCache', '$state', '$cordovaDialogs', '$ionicListDelegate', '$rootScope',
  function ($scope, GroupService, $cordovaToast, $ionicModal, GroupService, $timeout, AppCache, $state, $cordovaDialogs, $ionicListDelegate, $rootScope) {

    $scope.$on('$ionicView.beforeEnter', function () {
      $ionicModal.fromTemplateUrl('templates/modal/createGroupModal.html', {
        scope: $scope,
        animation: 'slide-in-up'
      }).then(function (modal) {
        $scope.modal = modal;
      });
      //表单验证提示
      $scope.nameErrorTips = {
        required: '请填写群名'
      };
      $scope.descriptionErrorTips = {
        required: '请填写群描述'
      };
      $scope.data = {};
      $scope.groups = [];
      /**
       * form表单提交
       */
      $scope.submit = function () {
        GroupService.createGroup($scope.data).then(function (result) {
          $scope.modal.hide();
          $scope.data = {};
          $cordovaToast.showShortCenter('创建成功');
        }, function (error) {
          $cordovaToast.showShortCenter(error.message);
        })
      };
      /**
       * 下拉刷新处理
       */
      $scope.doRefresh = function () {

        console.log("doRefresh....");

        GroupService.getGroupList().then(function (result) {
          //alert(angular.toJson(result));
          $scope.groups = result.groupList;
          for (var idx = 0; idx < result.groupList.length; idx++) {
            var item = result.groupList[idx];
            item.avatarLabel = item.name.charAt(0);
          }

        }, function (error) {
          //  $scope.$broadcast('scroll.refreshComplete');
          $cordovaToast.showShortCenter(error.message);
        }).finally(function () {
          $scope.$broadcast('scroll.refreshComplete');
        });
      }

      /**
       * 调整到聊天页面
       * @param group
       */
      $scope.toChat = function (group) {
        AppCache.put('group', group);
        $state.go('policeGroupChat');
      }

      $timeout(function () {
        $scope.doRefresh();
      }, 300);

      // A confirm dialog
      $scope.showConfirm = function (group) {
        $cordovaDialogs.confirm('群解散后不能恢复,您确定要解散吗?', '温馨提示', ['取消', '确定'])
          .then(function (buttonIndex) {

            if (buttonIndex == 2) {

              GroupService.dissolveGroup(group).then(function (result) {
                $cordovaToast.showShortCenter('解散成功');
                $scope.doRefresh();
              }, function (error) {
                $cordovaToast.showShortCenter(error.message);
              })

            }
          });

      };
      $scope.remove = function (group) {

        $ionicListDelegate.closeOptionButtons();

        $scope.showConfirm(group);

      };
    });


  }]);


/**
 * 群设置
 */
app.controller('PoliceGroupSettingCtrl', ['$scope', '$ionicModal', 'AppCache', 'GroupService', '$cordovaToast', '$timeout',
  '$cordovaDialogs', '$ionicListDelegate', 'localStorageService',
  function ($scope, $ionicModal, AppCache, GroupService, $cordovaToast, $timeout, $cordovaDialogs, $ionicListDelegate, localStorageService) {


    $scope.$on('$ionicView.beforeEnter', function () {
      $ionicModal.fromTemplateUrl('templates/modal/modifyGroupModal.html', {
        scope: $scope,
        animation: 'slide-in-up'
      }).then(function (modal) {
        $scope.modal = modal;
      });
      $ionicModal.fromTemplateUrl('templates/modal/addGroupMemberModal.html', {
        scope: $scope,
        animation: 'slide-in-up'
      }).then(function (modal) {
        $scope.addGroupMemberModal = modal;
      });
      $scope.group = AppCache.get('group') || {};

      //200ms后开始获取成员列表信息
      $timeout(function () {
        $scope.doRefresh();
      }, 200);

      //表单验证提示
      $scope.nameErrorTips = {
        required: '请填写群名'
      };
      $scope.descriptionErrorTips = {
        required: '请填写群描述'
      };
      $scope.submit = function () {
        //alert(angular.toJson($scope.group));
        GroupService.modifyGroup($scope.group).then(function (result) {
          $scope.modal.hide();
          $scope.data = {};
          $cordovaToast.showShortCenter('修改成功');
        }, function (error) {
          $cordovaToast.showShortCenter(error.message);
        })
      };

      $scope.newMember = {};
      //下拉刷新
      $scope.doRefresh = function () {
        GroupService.getMemberList($scope.group.id).then(function (result) {
          $scope.group.members = result.members;
        }, function (error) {
          $cordovaToast.showShortCenter(error.message);
        }).finally(function () {
          $scope.$broadcast('scroll.refreshComplete');
        });
      }
      /**
       * T出群成员
       * @param memberUserId
       */
      $scope.kickMember = function (memberUserId) {
        $scope.showkickMemberConfirm(memberUserId);
      }

      $scope.clearChatHistory = function (group) {
        $cordovaDialogs.confirm('您确定要情况聊天记录吗?', '温馨提示', ['取消', '确定'])
          .then(function (buttonIndex) {

            if (buttonIndex == 2) {
              //
              $cordovaToast.showShortCenter('清楚成功');
              var groupHistoricalChatsKey = $scope.group.id + "historicalChats";
              localStorageService.update(groupHistoricalChatsKey, []);
            }
          });


      };

      // A confirm dialog
      $scope.showkickMemberConfirm = function (memberUserId) {
        $cordovaDialogs.confirm('您确定要将该成员从群中移除吗?', '温馨提示', ['取消', '确定'])
          .then(function (buttonIndex) {
            if (buttonIndex == 2) {
              GroupService.removeMember(memberUserId, $scope.group.id).then(function (result) {
                $cordovaToast.showShortCenter('移除成功');
                $scope.doRefresh();
              }, function (error) {
                $cordovaToast.showShortCenter(error.message);
              })

            }
          }).finally(function () {
          $ionicListDelegate.closeOptionButtons();
        });

      };

      /**
       *  添加成员
       */
      $scope.addMember = function () {

        if (!$scope.newMember.otherLoginName) {
          $cordovaToast.showLongCenter("请输入用户登录名");
          return;
        }


        GroupService.addGroupMember($scope.newMember.otherLoginName, $scope.group.id).then(function (result) {
          $cordovaToast.showShortCenter('添加成功');
          $scope.addGroupMemberModal.hide();
        }, function (error) {
          $cordovaToast.showShortCenter(error.message);
        })
      };
    });
  }]);

app.controller('PoliceGroupChatCtrl',
  ['$rootScope', '$scope', '$timeout', 'AppCache', '$ionicScrollDelegate', '$log', 'AppSettings', 'socketFactory', '$rootScope', 'Storage', 'localStorageService',
    function ($rootScope, $scope, $timeout, AppCache, $ionicScrollDelegate, $log, AppSettings, socketFactory, $rootScope, Storage, localStorageService) {

      try {
        $scope.group = AppCache.get('group');
        $scope.groupName = $scope.group.name;
      } catch (e) {

      }
      $scope.$on('$ionicView.beforeLeave', function () {
        /**
         * 离开群房间
         */
        $scope.mySocket.emit('exitGroupRoomEvent', {groupId: $scope.group.id});
      });
      $scope.$on('$ionicView.afterEnter', function () {


        var myIoSocket = io.connect(AppSettings.chatEndpoint);
        $scope.mySocket = socketFactory({
          ioSocket: myIoSocket
        });
        /**
         * socket 断开事件
         */
        $scope.mySocket.on('disconnect', function (data) {
          console.log("disconnect:" + data)
          //广播事件
          $scope.socketConnectStatus =  $scope.mySocket.getConnectStatus();

          console.log('App.run:已经与服务器断开了连接!!!!');
        });
        $scope.mySocket.on('welcome', function (data) {
          console.log('mySocket.welcome:收到服务器的消息:' + data);
        });
        /**
         * socket连接事件
         */
        $scope.mySocket.on('connect', function () {
          $scope.socketConnectStatus = $scope.mySocket.getConnectStatus();
          console.log("App.run:已经连接到服务器....");
          console.log('scoket.on.connect:' +  $scope.socketConnectStatus);
          var userToken = Storage.getUserToken();
          $scope.mySocket.emit('initEvent', {accessToken: userToken.accessToken, tokenSecret: userToken.tokenSecret,groupId: $scope.group.id});


          $rootScope.$broadcast('socketConnect');
        });

        /**
         * 聚焦到底部
         */
        $timeout(function () {
          $ionicScrollDelegate.scrollBottom(true);
        }, 200);


        $scope.socketConnectStatus = $scope.mySocket.getConnectStatus();


        console.log('$scope.socketConnectStatus:' +  $scope.socketConnectStatus);


        $scope.mySocket.on('enterGroupRoomEvent', function (data) {

        })

        var groupHistoricalChatsKey = $scope.group.id + "historicalChats";

        $scope.$on('reInitData', function (data) {
          console.log('reInitData 事件出触发:' + data);

          var userToken = Storage.getUserToken();
          $scope.mySocket.emit('initEvent', {accessToken: userToken.accessToken, tokenSecret: userToken.tokenSecret});
          $timeout(function () {
            $scope.mySocket.emit('enterGroupRoomEvent', {groupId: $scope.group.id});
          }, 50);

        });
        $scope.lastMessageId = '';
        $scope.mySocket.on('new message', function (data) {
          console.log("......new Message:" + angular.toJson(data));
          if (data.chatContent && data.userName && data.groupId == $scope.group.id) {
            if (data.id == $scope.lastMessageId) {
              console.log('重复消息....');
              return;
            }
            $scope.lastMessageId = data.id;
            //if (Storage.get("userName") == data.userName) {
            //  data.isFromeMe = true;
            //} else {
            //  data.isFromeMe = false;
            //}
            $scope.historicalChats.push(data);
            localStorageService.update(groupHistoricalChatsKey, $scope.historicalChats);

            $ionicScrollDelegate.scrollBottom(true);
          }
        });


        $scope.mySocket.on('offlineMessage', function (messages) {
          console.log("......offlineMessage:" + angular.toJson(messages));
          if (!messages) {
            return;
          }
          for (var idx = 0; idx < messages.length; idx++) {
            var data = messages[idx];

            if (data.chatContent && data.userName && data.groupId == $scope.group.id) {
              //if (Storage.get("userName") == data.userName && data.groupId == $scope.group.id) {
              //  data.isFromeMe = true;
              //} else {
              //  data.isFromeMe = false;
              //}
              $scope.historicalChats.push(data);
              localStorageService.update(groupHistoricalChatsKey, $scope.historicalChats);
            }
          }
          if (messages.length > 0) {
            $ionicScrollDelegate.scrollBottom(true);
          }
        });


        $scope.showTime = true;

        /**
         * 从历史记录中获取聊天记录
         */
        $scope.historicalChats = localStorageService.get(groupHistoricalChatsKey, []);

        var userToken = Storage.getUserToken();
        $scope.sendMessage = function () {
          var sendData = {
            accessToken: userToken.accessToken, tokenSecret: userToken.tokenSecret,
            groupId: $scope.group.id, userName: Storage.get('userName'), chatContent: $scope.send_content
          };

          $scope.mySocket.emit('new message', sendData);

          $scope.send_content = "";
        };

        $timeout(function () {
          $scope.sendMessage();
        }, 100);


      });



    }])

